package com.changcheng.controller;
import com.alibaba.fastjson.JSON;
import com.changcheng.pojo.Article;
import com.changcheng.pojo.User;
import com.changcheng.service.ArticleService;
import com.changcheng.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(tags = "文章")
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;

    @PostMapping("/addArticle")
    @ApiOperation(value="新增文章内容")
    //新增文章内容
    public R add(Article article) {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //获取当地时间
        article.setCreateTime(LocalDate.now());
//        article.setUser_id(user.getId());
        articleService.add(article);
        return R.ok("新增成功！");
    }
    //删除文章内容
    @DeleteMapping("/deleteArticle")
    @ApiOperation(value="删除文章内容")
    public R delete(Integer id) {
        articleService.delete(id);
        return R.ok("删除成功！");
    }
    //修改文章内容
    @PutMapping("/updateArticle")
    @ApiOperation(value="修改文章内容")
    public R update(Article article) {
        //获取当地时间
        article.setUpdateTime(LocalDate.now());
        articleService.update(article);
        return R.ok("修改成功！");
    }
    @ApiOperation(value="查询所有文章")
    @GetMapping("/select")
    //查询文章的内容
    public String article(Article article, Integer currentPage) {
        System.out.println("currentPage:" + currentPage);
        HashMap<String, Object> res = new HashMap<>();
        List<Article> articles = articleService.article(article,currentPage);
        System.out.println("articles:" + articles);
        //如果查询结果不为空
        if(articles.size()>0){
            res.put("flag",0);
            res.put("data",articles);
        }
        //如果查询结果为空
        else{
            res.put("flag",1);
        }
        return JSON.toJSONString(res);
    }
    @ApiOperation(value="查询文章数量")
    @GetMapping("/selectItemsNumber")
    public int selectItemsNumber(Article article){
        return articleService.selectItemNum(article);
    }
}
